/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lps.server.processor;

import com.brs.action.LoginAction;
import com.brs.model.User;
import com.brs.response.LoginResponse;
import com.brs.response.Response;
import com.brs.server.ServerActionListener;
import com.brs.server.DBUtil;
import com.brs.server.SessionManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author phichidev
 */
public class LoginProcessor implements ServerActionListener<LoginAction> {

    public Response performed(LoginAction action) throws Exception {
        return doLogin(action);
    }

    /**
     * Change Password
     * @param LoginAction
     * @return LoginResponse
     * @throws SQLException
     */
    private Response doLogin(LoginAction action) throws SQLException {
        LoginResponse response = new LoginResponse();        
        PreparedStatement ps = DBUtil.getConnection().prepareStatement(
                "SELECT * FROM [User] WHERE UserName = ? AND Password = ?");
        ps.setString(1, action.getUsername());
        ps.setString(2, action.getPassword());

        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            User user = new User();
            user.setUserID(rs.getInt("UserID"));
            user.setUserName(rs.getString("FullName"));
            user.setDepartment(rs.getInt("Department"));
            response.setUser(user);

            String sessionId = SessionManager.newSession(user);
            response.setSessionId(sessionId);
            response.setCode(Response.OK);
        } else {
            response.setCode(Response.FAIL);
            response.setMessage("Username or Password incorrect!");
        }
        return response;
    }
}
